package com.colin.aiyi.ui.Home.chudao;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.colin.aiyi.R;
import com.colin.aiyi.adapter.MeAdapter;
import com.colin.aiyi.adapter.RoleAdapter;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.entity.Chudao;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.response.BaseResponse;
import com.colin.aiyi.entity.response.ChuDaoRespone;
import com.colin.aiyi.entity.response.RoleResponse;
import com.colin.aiyi.fragment.BaseFragment;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.view.ShowMsgUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by hl on 2017/5/8.
 * 我要出道，一鸣惊人
 */

public class ReferrerFragment extends BaseFragment implements View.OnClickListener, IViewReferrer {


    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.recycler_view_role_v1)
    RecyclerView recyclerViewRoleV1;
    @BindView(R.id.text_edit_v2)
    TextView textEditV2;
    @BindView(R.id.img_header)
    CircleImageView imgHeader;
    @BindView(R.id.text_title)
    TextView textTitle;
    @BindView(R.id.text_tag_v2)
    TextView textTagV2;

    @BindView(R.id.text_url_title_v2)
    TextView textUrlTitleV2;
    @BindView(R.id.text_url_decs_v2)
    TextView textUrlDecsV2;
    @BindView(R.id.edit_decs_v1)
    EditText editDecsV1;
    @BindView(R.id.recycler_view_v1)
    RecyclerView recyclerViewV1;
    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.line_button)
    LinearLayout lineButton;
    @BindView(R.id.text_decs_v1)
    TextView textDecsV1;
    @BindView(R.id.text_decs_v2)
    TextView textDecsV2;
    private Chudao chudao;
    private Chudao chudaoEdit = new Chudao();
    private MeAdapter meAdapter;
    private RoleAdapter roleAdapter;
    private User user;
    private Unbinder unbinder;
    private String json;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = SharePreferenceUtil.getObject(getContext(), User.class);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_fragment_referrer, null);
        unbinder = ButterKnife.bind(this, view);
        editDecsV1= (EditText) view.findViewById(R.id.edit_decs_v1);
        iPresenter = ImpPYiMing.getInstance(this);
        initView(inflater);
        return view;
    }


    @Override
    protected void lazyLoad() {
        user = SharePreferenceUtil.getObject(getContext(), User.class);
        if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
            Intent intent = new Intent(getContext(), LoginAc.class);
            intent.putExtra("FromAc", Constant.MIAN);
            startActivity(intent);
            return;
        }
        chudaoEdit.setAccessToken(user.getAccessToken());
        // iPresenter.audio_detail(user);
        user.setCode("userRole");
        iPresenter.base_getListByCode(user);
        bindHeadView(user);
        // ShowMsgUtil.showLoadingDialog(getContext());
    }


    void bindHeadView(User user) {
        Glide.with(getContext()).load(Constant.BASE_URL + user.getHeadUrl()).error(R.mipmap.pic2).into(imgHeader);
        textTitle.setText(user.getUserName());
    }


    private void initView(LayoutInflater inflater) {
        meAdapter = new MeAdapter();
        meAdapter.setOnItemChildClickListener(iPresenter);
        Chudao.UrlsBean urlsBean=new Chudao.UrlsBean();
        urlsBean.setFrist(true);
        urlsBean.setLast(true);
        meAdapter.getData().add(urlsBean);
        recyclerViewV1.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewV1.setAdapter(meAdapter);
        textEditV2.setOnClickListener(this);
        roleAdapter = new RoleAdapter();
        roleAdapter.setOnItemClickListener(iPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewRoleV1.setLayoutManager(linearLayoutManager);
        recyclerViewRoleV1.setAdapter(roleAdapter);
        button2.setOnClickListener(iPresenter);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void roleView(RoleResponse response) {
        if (response.getCode() == 200 && response.getData().size() > 0) {
            roleAdapter.getData().clear();
            roleAdapter.getData().addAll(response.getData());
            roleAdapter.notifyDataSetChanged();
        }
        iPresenter.audio_detail(user);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.text_edit_v2, R.id.button1})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_edit_v2:
                swichStatus(1,chudaoEdit );
                break;
            case R.id.button1:
                if (chudao == null || chudao.getUrls() == null) {
                    swichStatus(3, null);
                }
                if (chudao != null) {
                    cancelEditToShow();
                }
                break;
        }
    }


    /**********
     * 切换模式
     * @param i   1  编辑模式， 2 展示模式
     * @param chudao
     */
    private void swichStatus(int i, Chudao chudao) {
        switch (i) {
            case 3://清空模式
                editDecsV1.setText("");
                meAdapter.getData().clear();
                Chudao.UrlsBean urlsBean=new Chudao.UrlsBean();
                urlsBean.setFrist(true);
                urlsBean.setLast(true);
                meAdapter.getData().add(urlsBean);
                meAdapter.notifyDataSetChanged();

                textEditV2.setVisibility(View.GONE);
                textTagV2.setVisibility(View.GONE);
                textDecsV2.setVisibility(View.GONE);
                textUrlTitleV2.setVisibility(View.GONE);
                textUrlDecsV2.setVisibility(View.GONE);

                recyclerViewRoleV1.setVisibility(View.VISIBLE);
                textDecsV1.setVisibility(View.VISIBLE);
                editDecsV1.setVisibility(View.VISIBLE);
                recyclerViewV1.setVisibility(View.VISIBLE);
                button1.setVisibility(View.VISIBLE);
                button2.setVisibility(View.VISIBLE);
                button1.setText("重置");
                return;
            case 1:
                textEditV2.setVisibility(View.GONE);
                textTagV2.setVisibility(View.GONE);
                textDecsV2.setVisibility(View.GONE);
                textUrlTitleV2.setVisibility(View.GONE);
                textUrlDecsV2.setVisibility(View.GONE);

                recyclerViewRoleV1.setVisibility(View.VISIBLE);
                textDecsV1.setVisibility(View.VISIBLE);
                editDecsV1.setVisibility(View.VISIBLE);
                recyclerViewV1.setVisibility(View.VISIBLE);
                button1.setVisibility(View.VISIBLE);
                button2.setVisibility(View.VISIBLE);
                break;
            case 2:
                textEditV2.setVisibility(View.VISIBLE);
                textTagV2.setVisibility(View.VISIBLE);
                textDecsV2.setVisibility(View.VISIBLE);
                textUrlTitleV2.setVisibility(View.VISIBLE);
                textUrlDecsV2.setVisibility(View.VISIBLE);

                recyclerViewRoleV1.setVisibility(View.GONE);
                textDecsV1.setVisibility(View.GONE);
                editDecsV1.setVisibility(View.GONE);
                recyclerViewV1.setVisibility(View.GONE);
                button1.setVisibility(View.GONE);
                button2.setVisibility(View.GONE);
                break;
            case 0:
                break;
        }
//        bindViewDate(chudao);
    }




    /******
     * 提交成功后跳转展示页
     */
    private void SuccessToShow(){
        chudaoEdit.setUrls(meAdapter.getData());
        chudaoEdit.setContent(editDecsV1.getText().toString());
        swichStatus(2, chudaoEdit);
        textDecsV2.setText(chudaoEdit.getContent());
        StringBuffer stringBuffer = new StringBuffer("");
        for (int j = 0; j < chudaoEdit.getUrls().size(); j++) {
            if (chudaoEdit.getUrls().get(j).getUrl()==null||
                    chudaoEdit.getUrls().get(j).getUrl().length()<1){

            }else {
                stringBuffer.append(chudaoEdit.getUrls().get(j).getUrl());
                if (j + 1 < chudaoEdit.getUrls().size())
                    stringBuffer.append("\n");
            }
        }
        textUrlDecsV2.setText(stringBuffer.toString());
        swichStatus(2,chudaoEdit);


    }

    /****
     * 取消编辑到展示页
     */
    private void cancelEditToShow() {
        getChudao(json);
        swichStatus(2,null);
    }

    /*********
     * 展示 从服务器获得的数据
     * @param chudao
     */
    private void showFromServer(Chudao chudao) {
        if (chudao == null || chudao.getUrls() == null) {
            button1.setText("重置");
            Chudao.UrlsBean urlsBean=new Chudao.UrlsBean();
            urlsBean.setFrist(true);
            urlsBean.setLast(true);
            meAdapter.getData().clear();
            meAdapter.getData().add(urlsBean);
            swichStatus(1,chudao);
            return;
        }
        button1.setText("取消");
        textTagV2.setText(chudao.getRoleName());
        textDecsV2.setText(chudao.getContent());
        StringBuffer stringBuffer = new StringBuffer("");
        for (int j = 0; j < chudao.getUrls().size(); j++) {
            if (chudao.getUrls().get(j).getUrl()==null||
                    chudao.getUrls().get(j).getUrl().length()<1){

            }else {
                stringBuffer.append(chudao.getUrls().get(j).getUrl());
                if (j + 1 < chudao.getUrls().size())
                    stringBuffer.append("\n");
            }
        }
        textUrlDecsV2.setText(stringBuffer.toString());

        editDecsV1.setText(chudao.getContent());
        if (chudao.getUrls() != null && chudao.getUrls().size() > 0) {
            chudao.getUrls().get(chudao.getUrls().size() - 1).setLast(true);
            chudao.getUrls().get(0).setFrist(true);
            if (chudao.getUrls()!=meAdapter.getData()){
                meAdapter.getData().clear();
                meAdapter.getData().addAll(chudao.getUrls());
            }
            meAdapter.notifyDataSetChanged();
        }
        for (int i = 0; i < roleAdapter.getData().size(); i++) {
            if (chudao.getRoleId() == roleAdapter.getData().get(i).getId()) {
                roleAdapter.getData().get(i).setSelcet(true);
                roleAdapter.notifyItemChanged(i);
                Set<String > set=new HashSet<>();
                set.add(chudao.getRoleName());
                set.add(chudao.getRoleId()+"");
                JPushInterface.setTags(context,set,null);
            }
        }
        swichStatus(2,chudao);
    }




    /*获取一鸣惊人资料并绑定到 填充到出道chudaoEdit里供编辑使用*/

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getChudao(String result) {
        ShowMsgUtil.hideLoadingDialog();
        json=result;
        ChuDaoRespone chuDaoRespone=gson.fromJson(result,ChuDaoRespone.class);
        if (chuDaoRespone==null){

        }
        if (chuDaoRespone.getCode()==200){
            chudao = chuDaoRespone.getData();
            chudao.setAccessToken(user.getAccessToken());
            showFromServer(chudao);
        }else if (chuDaoRespone.getCode() == 400) {
            swichStatus(3,null);
        } else {
            showMsg(chuDaoRespone.getMessage());
        }
    }



    @Override
    public <T> void refreshStatus(T t) {
        BaseResponse baseResponse = (BaseResponse) t;
        if (baseResponse.getCode() == 200) {
            SuccessToShow();
        }else {
            if (baseResponse.getCode()==400){
                if (baseResponse.getMessage().equals("已经添加一鸣惊人")){
                    chudao=new Chudao();
                    chudao.setContent(editDecsV1.getText().toString());
                    iPresenter.onClick(button2);
                }
            }
        }

    }

    @Override
    public Context getContextF() {
        return getContext();
    }

    @Override
    public String getContent() {
        if (editDecsV1==null)
        {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_fragment_referrer, null);
            editDecsV1= (EditText) view.findViewById(R.id.edit_decs_v1);
            return editDecsV1.getText().toString().replace(" ", "");
        }
        return editDecsV1.getText().toString().replace(" ", "");
    }

    @Override
    public boolean isUpadate() {
        return chudao != null;
    }

    @Override
    public MeAdapter getAdapter() {
        return meAdapter;
    }
}
